package cn.com.haopy.yue.ai.admin.service;


import cn.com.haopy.yue.ai.core.config.wx.WxMaProperties;
import cn.com.haopy.yue.ai.core.enums.PayStatusCode;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.db.entity.arisk.AIRiskOrder;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSUser;
import cn.com.haopy.yue.ai.db.service.hos.AIRiskOrderService;
import cn.com.haopy.yue.ai.db.service.hos.HOSUserService;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Objects;

/**
 * 微信支付
 */
@Service
@Slf4j
public class AdminOrderService {

    @Autowired
    @Qualifier("wxMaPayService")
    private WxPayService wxMaPayService;

    @Autowired
    private WxMaProperties wxMaProperties;

    @Autowired
    private AIRiskOrderService orderService;

    @Autowired
    private HOSUserService userService;


    /**
     * 订单退款
     *
     * @param id
     * @return
     */
    @Transactional
    public Object wxRefundOrder(Integer id) {

        try {
            AIRiskOrder order = orderService.getById(id);
            if (Objects.isNull(order)) {
                return ResponseUtil.fail("订单不存在！");
            }

            if (!order.getPayStatus().equals(PayStatusCode.REFUNDING.getCode())) {
                return ResponseUtil.fail("订单不在退款状态！");
            }

            WxPayRefundResult result = this.wxRefund(order.getOrderNo(), order.getOrderPrice());

            if (Objects.nonNull(result) && result.getReturnCode().equals("SUCCESS")) {


                HOSUser user = userService.getById(order.getUserId());
                LocalDate endDate = user.getVipEndDate();
                endDate = endDate.plusMonths(-order.getMonths());

                LocalDate now = LocalDate.now();
                //减了以后，小于现在，则设置为现在
                if (endDate.isBefore(now)) {
                    endDate = now;
                }
                user.setVipEndDate(endDate);
                userService.updateById(user);

                //订单状态设置
                order.setPayStatus(PayStatusCode.REFUND.getCode());
                orderService.updateById(order);


                return ResponseUtil.ok();
            }

            if (Objects.nonNull(result)) {
                return ResponseUtil.fail(result.getErrCodeDes());
            }


        } catch (Exception e) {
            log.error(e.toString());
            return ResponseUtil.fail(e.getMessage());
        }
        return ResponseUtil.fail();


    }


    /**
     * 退款
     *
     * @param orderNo
     * @param orderFee
     * @return
     */
    private WxPayRefundResult wxRefund(String orderNo, BigDecimal orderFee) throws Exception {


        // 微信退款
        WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
        wxPayRefundRequest.setOutTradeNo(orderNo);
        wxPayRefundRequest.setOutRefundNo("refund_" + orderNo);
        // 元转成分
        Integer totalFee = orderFee.multiply(new BigDecimal(100)).intValue();
        wxPayRefundRequest.setTotalFee(totalFee);
        wxPayRefundRequest.setRefundFee(totalFee);

        return wxMaPayService.refund(wxPayRefundRequest);


    }
}
